/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bm.main.threading;

import com.bm.setting.ServerConfig;
import com.bm.template.IProcessor;
import com.bm.template.RequestAdapter;
import com.bm.util.MessagePrinter;
import com.bm.util.Util;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author ssm
 */
public class RequestTransaksi implements Runnable {

    private int maksimum_data_per_request;
    private String url;

    public RequestTransaksi(int maksimum_data_per_request, String url) {
        this.maksimum_data_per_request = maksimum_data_per_request;
        this.url = url;
    }

    @Override
    public void run() {
        while (true) {
            int waiting_interval = 15;
            String data = Util.doRequestWithTimeout("", url + "/request_waiting_transaksi/" + this.maksimum_data_per_request, false, 30000, 1);
            if (data.trim().equalsIgnoreCase("none")) {
                MessagePrinter.print("Tidak ada transaksi");
            } else {
                JsonArray jsaResp = new JsonArray();

                JsonParser jse = new JsonParser();

                JsonArray jsa = null;
                try {
                    jsa = jse.parse(data).getAsJsonArray();
                } catch (Exception e) {
                    System.out.println("Error Parsing web " + e.getMessage());
                    try {
                        Thread.sleep(15 * 1000);
                    } catch (InterruptedException ex) {
                        System.out.println(ex.getMessage());
                    }
                    continue;
                }

                for (int i = 0; i < jsa.size(); i++) {
                    waiting_interval--;
                    JsonObject jso = jsa.get(i).getAsJsonObject();
                    MessagePrinter.print("Memproses " + (i + 1) + " dari " + jsa.size() + " transaksi (id_request : " + jso.get("id_request").getAsString() + ")");
                    long nilai_transaksi = (jso.get("harga_jual").getAsLong() + jso.get("nominal_custom").getAsLong()) * jso.get("jumlah_beli").getAsLong();
                    if (cek_saldo_member(jso.get("id_member").getAsLong(), nilai_transaksi)) {
                        String id_produk = jso.get("id_produk").getAsString();
                        IProcessor processor = RequestAdapter.getProcessor(id_produk, jso);
                        if (processor == null) {
                            JsonObject jsoResp = new JsonObject();
                            jsoResp.add("id_request", jso.get("id_request"));
                            jsoResp.add("status", jse.parse("-2"));
                            jsoResp.add("keterangan", jse.parse("'produk " + id_produk + " tidak ditemukan'"));
                        } else {
                            jsaResp.add(processor.getResponse());
                        }
                    } else {
                        JsonObject jsoResp = new JsonObject();
                        jsoResp.add("id_request", jso.get("id_request"));
                        jsoResp.add("status", jse.parse("-2"));
                        jsoResp.add("keterangan", jse.parse("'saldo tidak mencukupi'"));
                        jsaResp.add(jsoResp);
                    }
                }
                Util.doRequestWithTimeout(jsaResp.toString(), url + "/update_status_transaksi", true, 30000, 1);
            }
            try {
                if (waiting_interval <= 0) {
                    MessagePrinter.print("Menunggu proses transaksi berikutnya selama " + waiting_interval + " detik");
                    Thread.sleep(2 * 1000);
                    continue;
                }
                MessagePrinter.print("Menunggu proses transaksi berikutnya selama " + waiting_interval + " detik");
                Thread.sleep(waiting_interval * 1000);
            } catch (InterruptedException ex) {
                MessagePrinter.printDebug(ex.getMessage());
            }
        }
    }

    public boolean cek_saldo_member(long id_member, long nilai_transaksi) {
        Connection conn = ServerConfig.getConnection();
        PreparedStatement pst = null;
        ResultSet rs = null;
        try {
            pst = conn.prepareStatement("select id_member from kamisa.member where id_member = ? and saldo >= ?");
            pst.setLong(1, id_member);
            pst.setLong(2, nilai_transaksi);
            rs = pst.executeQuery();
            while (rs.next()) {
                return true;
            }
        } catch (SQLException ex) {
            Logger.getLogger(RequestTransaksi.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            ServerConfig.close(rs);
            ServerConfig.close(pst);
            ServerConfig.close(conn);
        }
        return false;
    }
}
